import datetime

from django.db import models
from django.urls import reverse
from django.utils.text import slugify

from pypinyin import lazy_pinyin


class CustomManager(models.Manager):
    def all(self):
        return self.filter(is_deleted=False)

    def get_deleted(self):
        return self.filter(is_delleted=True)


class Network(models.Model):
    """
    台网信息
    """
    NET_STATUS = (
        (0, '运行'),
        (1, '测试'),
        (2, '下线')
    )
    code = models.CharField(max_length=10, unique=True, verbose_name="台网代码")
    slug = models.SlugField(editable=False)
    name_zh = models.CharField(max_length=64, null=True, blank=True, verbose_name="台网名称(中文)")
    name_en = models.CharField(max_length=64, null=True, blank=True, verbose_name="台网名称(英文)")
    start_date = models.DateField("开始时间", null=True, blank=True)
    end_date = models.DateField("结束时间", null=True, blank=True)
    # min_longitude = models.FloatField(null=True, blank=True, verbose_name="台网最小经度")
    # max_longitude = models.FloatField(null=True, blank=True, verbose_name="台网最大经度")
    # min_latitude = models.FloatField(null=True, blank=True, verbose_name="台网最小纬度")
    # max_latitude = models.FloatField(null=True, blank=True, verbose_name="台网最大纬度")
    status = models.PositiveSmallIntegerField(choices=NET_STATUS, default=0, verbose_name="台网状态")
    describe = models.TextField(blank=True, null=True, verbose_name="台网描述")

    c_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    m_time = models.DateTimeField(auto_now=True, verbose_name="更新日期")

    is_deleted = models.BooleanField(default=False, verbose_name='是否删除')

    objects = CustomManager()

    class Meta:
        verbose_name = "台网信息"
        verbose_name_plural = "台网信息"

    def __str__(self):
        return self.code

    def save(self, *args, **kwargs):
        self.slug = slugify(self.code)
        self.code = self.code.upper()
        if self.name_zh and not self.name_en:
            self.name_en = ''.join(lazy_pinyin(self.name_zh, strict=False))

        super(Network, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse("seisnet:network", kwargs={"code": self.code})


def set_default_network():
    return Network.objects.get(code="XX").pk


class Station(models.Model):
    """
    台站信息
    """
    STATION_STATUS = (
        (0, '运行'),
        (1, '测试'),
        (2, '故障'),
        (3, '暂停'),
        (4, '下线')
    )
    network = models.ForeignKey('Network', default=set_default_network, on_delete=models.SET_DEFAULT,
                                verbose_name="所属台网")
    code = models.CharField(max_length=10, verbose_name="台站代码")
    slug = models.SlugField(editable=False)
    name_zh = models.CharField(max_length=64, null=True, blank=True, verbose_name="台站名称(中文)")
    name_en = models.CharField(max_length=64, null=True, blank=True, verbose_name="台站名称(英文)")
    longitude = models.FloatField(default=0.0, verbose_name="台站经度")
    latitude = models.FloatField(default=0.0, verbose_name="台站纬度")
    altitude = models.FloatField(default=0.0, verbose_name="台站高程")
    status = models.PositiveSmallIntegerField(choices=STATION_STATUS, default=0, verbose_name="台站状态")
    location = models.TextField(null=True, blank=True, verbose_name="位置描述")
    describe = models.TextField(null=True, blank=True, verbose_name="台站描述")

    c_date = models.DateField(default=datetime.date(2011, 1, 1), verbose_name="台站建成日期")
    m_date = models.DateField(default=datetime.date(2011, 1, 1), verbose_name="台站最近修改日期")
    e_date = models.DateField(null=True, blank=True, verbose_name='台站结束观测日期')

    c_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    m_time = models.DateTimeField(auto_now=True, verbose_name="更新日期")

    is_deleted = models.BooleanField(default=False, verbose_name='是否删除')

    objects = CustomManager()

    class Meta:
        verbose_name = "台站信息"
        verbose_name_plural = "台站信息"
        unique_together = ('network', 'code')

    def __str__(self):
        return "{network}/{code}".format(
            network=self.network,
            code=self.code,
        )

    def save(self, *args, **kwargs):
        self.slug = slugify(self.code)
        self.code = self.code.upper()
        if self.name_zh and not self.name_en:
            self.name_en = ''.join(lazy_pinyin(self.name_zh, strict=False))

        super(Station, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse("seisnet:station_detail", kwargs={"network_code": self.network, "code": self.code})
